package com.ygqh.baby.service.impl;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.config.SmsConfig;
import com.ygqh.baby.service.SmsService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.utils.CommonUtil;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.WebUtil;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: sunshuo
 * @date: 2018/11/26 14:57
 */
@Service
public class SmsServiceImpl implements SmsService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final SmsConfig smsConfig;

	@Autowired
	public SmsServiceImpl(SmsConfig smsConfig) {
		this.smsConfig = smsConfig;
	}

	@Override
	public void sendSms(String phone, String content) {
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(smsConfig.getUrl());
			httpPost.setEntity(getUefEntity(phone, content));
			logger.info("sendSms request: {}, content: {}", httpPost.getURI(), content);
			executeRequest(httpClient, httpPost);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
			logger.error("短信息发送失败,手机号：{}, 内容：{}", phone, content);
		} finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void sendSms(String phone, String content, String url) {
		content = content + WebUtil.generateShortUrl(url);
		sendSms(phone, content);
	}

	private UrlEncodedFormEntity getUefEntity(String phone, String content) throws UnsupportedEncodingException {
		List<BasicNameValuePair> formparams = new ArrayList<>(7);
		formparams.add(new BasicNameValuePair("userId", smsConfig.getUserId()));
		formparams.add(new BasicNameValuePair("password", smsConfig.getPassword()));
		formparams.add(new BasicNameValuePair("pszMobis", phone));
		formparams.add(new BasicNameValuePair("pszMsg", content));
		formparams.add(new BasicNameValuePair("iMobiCount", smsConfig.getiMobiCount()));
		formparams.add(new BasicNameValuePair("pszSubPort", smsConfig.getPszSubPort()));
		formparams.add(new BasicNameValuePair("MsgId", smsConfig.getMsgId()));
		return new UrlEncodedFormEntity(formparams, "UTF-8");
	}

	private void executeRequest(CloseableHttpClient httpClient, HttpPost httpPost) {
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			logger.info("sendSms response: {}", entity != null ? JSON.toJSONString(entity) : "");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("sendSms error: {}", ExceptionUtil.getExceptionMsg(e));
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
